import datetime
import backtrader as bt
from strategies import *

# 初始化Cerebro引擎
cerebro = bt.Cerebro(optreturn=False)

#设置数据参数并添加至Cerebro引擎
data = bt.feeds.YahooFinanceCSVData(
	dataname='TSLA.csv',
	fromdate=datetime.datetime(2016, 1, 1),
	todate=datetime.datetime(2017, 12, 31))

cerebro.adddata(data)

# 向Cerebro引擎添加分析器类
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe_ratio')

# 向Cerebro引擎添加策略类及待优化参数的取值范围
cerebro.optstrategy(MAcrossover, pfast=range(5, 20), pslow=range(50, 100))



# 头寸设置
cerebro.addsizer(bt.sizers.SizerFix, stake=3)

if __name__ == '__main__':
	optimized_runs = cerebro.run()

	final_results_list = []
	#在由列表构成的列表中迭代
	for run in optimized_runs:
		for strategy in run:
			PnL = round(strategy.broker.get_value() - 10000,2)
			sharpe = strategy.analyzers.sharpe_ratio.get_analysis()
			final_results_list.append([strategy.params.pfast, strategy.params.pslow, PnL, sharpe['sharperatio']])

	sort_by_sharpe = sorted(final_results_list, key=lambda x: x[3], reverse=True)
	#打印以夏普比率为基准的最优的五个结果
	for line in sort_by_sharpe[:5]:
		print(line)